using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.ClassroomManagement
{
    public partial class ClassroomListForm : Form
    {
        private ClassroomBLL _classroomBLL;
        private User _currentUser;

        public ClassroomListForm(User currentUser)
        {
            InitializeComponent();
            _classroomBLL = new ClassroomBLL();
            _currentUser = currentUser;
            InitializeDataGridView();
            LoadClassrooms();
            SetupRolePermissions();
            
            // 设置为合适的大小
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(900, 600);
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void SetupRolePermissions()
        {
            // 根据用户角色设置不同的权限
            if (_currentUser.Role == UserRole.Student)
            {
                // 学生可以查看教室列表，但只能进行预约操作
                btnAdd.Enabled = false;
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
                // 可以在这里添加预约按钮的显示逻辑
                this.Text = "教室预约";
            }
            else if (_currentUser.Role != UserRole.Administrator && _currentUser.Role != UserRole.Staff)
            {
                // 其他非管理员角色（如教师）禁用管理功能
                btnAdd.Enabled = false;
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
            }
        }

        private void InitializeDataGridView()
        {
            // 设置DataGridView列
            dataGridViewClassrooms.AutoGenerateColumns = false;
            dataGridViewClassrooms.Columns.AddRange(new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn { HeaderText = "教室ID", DataPropertyName = "ClassroomID" },
                new DataGridViewTextBoxColumn { HeaderText = "教室编号", DataPropertyName = "ClassroomNumber" },
                new DataGridViewTextBoxColumn { HeaderText = "教室类型", DataPropertyName = "Type" },
                new DataGridViewTextBoxColumn { HeaderText = "容量", DataPropertyName = "Capacity" },
                new DataGridViewTextBoxColumn { HeaderText = "位置", DataPropertyName = "Location" },
                new DataGridViewTextBoxColumn { HeaderText = "设备情况", DataPropertyName = "Equipment" }
            });

            // 设置DataGridView属性
            dataGridViewClassrooms.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridViewClassrooms.MultiSelect = false;
        }

        private void LoadClassrooms()
        {
            var classrooms = _classroomBLL.GetAllClassrooms();
            dataGridViewClassrooms.DataSource = classrooms;
            FormatDataGridView();
        }

        private void FormatDataGridView()
        {
            // 处理教室类型枚举显示
            if (dataGridViewClassrooms.Columns["Type"] is DataGridViewColumn typeColumn)
            {
                // 隐藏原始Type列
                typeColumn.Visible = false;
                
                // 添加新的类型文本列（如果不存在）
                if (!dataGridViewClassrooms.Columns.Contains("TypeText"))
                {
                    dataGridViewClassrooms.Columns.Add("TypeText", "教室类型");
                }
                
                // 填充类型文本
                foreach (DataGridViewRow row in dataGridViewClassrooms.Rows)
                {
                    // 先获取并检查Type单元格
                    DataGridViewCell typeCell = row.Cells["Type"];
                    DataGridViewCell typeTextCell = row.Cells["TypeText"];
                    if (typeCell?.Value != null && typeTextCell != null)
                    {
                        // 直接使用枚举值的字符串表示
                        typeTextCell.Value = typeCell.Value.ToString();
                    }
                    else if (typeTextCell != null)
                    {
                        typeTextCell.Value = "未知类型";
                    }
                }
            }
            
            // 重命名位置列标题
            if (dataGridViewClassrooms.Columns["Building"] is DataGridViewColumn buildingColumn && !dataGridViewClassrooms.Columns.Contains("Location"))
            {
                buildingColumn.HeaderText = "位置";
            }
        }
        private void InitializeComponent()
        {
            this.dataGridViewClassrooms = new System.Windows.Forms.DataGridView();
            this.btnAdd = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.comboBoxTypeFilter = new System.Windows.Forms.ComboBox();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewClassrooms)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.tableLayoutPanel2.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel1.ColumnCount = 5;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 75F));
            this.tableLayoutPanel1.Location = new System.Drawing.Point(20, 20);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 1;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(750, 60);
            this.tableLayoutPanel1.TabIndex = 9;
            // 
            // tableLayoutPanel2
            // 
            this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel2.ColumnCount = 4;
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Location = new System.Drawing.Point(20, 400);
            this.tableLayoutPanel2.Name = "tableLayoutPanel2";
            this.tableLayoutPanel2.RowCount = 1;
            this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Size = new System.Drawing.Size(750, 30);
            this.tableLayoutPanel2.TabIndex = 10;
            // 
            // dataGridViewClassrooms
            // 
            this.dataGridViewClassrooms.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridViewClassrooms.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewClassrooms.Location = new System.Drawing.Point(20, 100);
            this.dataGridViewClassrooms.Name = "dataGridViewClassrooms";
            this.dataGridViewClassrooms.RowHeadersWidth = 51;
            this.dataGridViewClassrooms.RowTemplate.Height = 27;
            this.dataGridViewClassrooms.Size = new System.Drawing.Size(750, 280);
            this.dataGridViewClassrooms.TabIndex = 0;

            // 
            // label1
            // 
            this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 22);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(74, 15);
            this.label1.TabIndex = 5;
            this.label1.Text = "搜索:";
            // 
            // txtSearch
            // 
            this.txtSearch.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.txtSearch.Location = new System.Drawing.Point(83, 19);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(184, 25);
            this.txtSearch.TabIndex = 6;
            this.txtSearch.TextChanged += new System.EventHandler(this.txtSearch_TextChanged);
            // 
            // label2
            // 
            this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(269, 22);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(74, 15);
            this.label2.TabIndex = 7;
            this.label2.Text = "类型:";
            // 
            // comboBoxTypeFilter
            // 
            this.comboBoxTypeFilter.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.comboBoxTypeFilter.FormattingEnabled = true;
            this.comboBoxTypeFilter.Items.AddRange(new object[] {
            "全部",
            "普通教室",
            "多媒体教室",
            "实验室",
            "语音室"});
            this.comboBoxTypeFilter.Location = new System.Drawing.Point(349, 19);
            this.comboBoxTypeFilter.Name = "comboBoxTypeFilter";
            this.comboBoxTypeFilter.Size = new System.Drawing.Size(184, 23);
            this.comboBoxTypeFilter.TabIndex = 8;
            this.comboBoxTypeFilter.Text = "全部";
            this.comboBoxTypeFilter.SelectedIndexChanged += new System.EventHandler(this.comboBoxTypeFilter_SelectedIndexChanged);
            // 
            // btnAdd
            // 
            this.btnAdd.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnAdd.Location = new System.Drawing.Point(3, 3);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(74, 24);
            this.btnAdd.TabIndex = 1;
            this.btnAdd.Text = "添加";
            this.btnAdd.UseVisualStyleBackColor = true;
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            // 
            // btnEdit
            // 
            this.btnEdit.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnEdit.Location = new System.Drawing.Point(83, 3);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(74, 24);
            this.btnEdit.TabIndex = 2;
            this.btnEdit.Text = "编辑";
            this.btnEdit.UseVisualStyleBackColor = true;
            this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnDelete.Location = new System.Drawing.Point(163, 3);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(74, 24);
            this.btnDelete.TabIndex = 3;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btnRefresh.Location = new System.Drawing.Point(672, 3);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(75, 24);
            this.btnRefresh.TabIndex = 4;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // ClassroomListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.ClientSize = new System.Drawing.Size(792, 453);
            this.Controls.Add(this.tableLayoutPanel2);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Controls.Add(this.dataGridViewClassrooms);
            this.Name = "ClassroomListForm";
            this.Text = "教室管理";
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.txtSearch, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.label2, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.comboBoxTypeFilter, 3, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnAdd, 0, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnEdit, 1, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnDelete, 2, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnRefresh, 3, 0);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewClassrooms)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.tableLayoutPanel2.ResumeLayout(false);
            this.ResumeLayout(false);
        }

        private void btnAdd_Click(object? sender, EventArgs e)
        {
            ClassroomEditForm form = new ClassroomEditForm(new Classroom());
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadClassrooms();
            }
        }

        private void btnEdit_Click(object? sender, EventArgs e)
        {
            if (dataGridViewClassrooms.SelectedRows.Count > 0)
            {
                object? boundItem = dataGridViewClassrooms.SelectedRows[0].DataBoundItem;
                if (boundItem is Classroom classroom)
                {                    // 由于使用了模式匹配，classroom已经被确保不为null
                    ClassroomEditForm form = new ClassroomEditForm(classroom);
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        LoadClassrooms();
                    }
                }
                else
                {
                    MessageBox.Show("无法获取教室信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的教室", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDelete_Click(object? sender, EventArgs e)
        {
            if (dataGridViewClassrooms.SelectedRows.Count > 0)
            {
                object? boundItem = dataGridViewClassrooms.SelectedRows[0].DataBoundItem;
                if (boundItem is Classroom classroom)
                {
                    if (MessageBox.Show($"确定要删除教室 '{classroom.ClassroomNumber}' 吗？", "确认", 
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                            {
                                _classroomBLL.DeleteClassroom(classroom.ClassroomID);
                                LoadClassrooms();
                                MessageBox.Show("教室已删除", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("无法获取教室信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的教室", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnRefresh_Click(object? sender, EventArgs e)
        {
            LoadClassrooms();
        }

        private void comboBoxTypeFilter_SelectedIndexChanged(object? sender, EventArgs e)
        {
            FilterAndSearch();
        }

        private void txtSearch_TextChanged(object? sender, EventArgs e)
        {
            FilterAndSearch();
        }

        private void FilterAndSearch()
        {
            string searchText = txtSearch.Text.Trim().ToLower();
            string typeFilter = comboBoxTypeFilter.SelectedItem?.ToString() ?? "全部类型";

            var allClassrooms = _classroomBLL.GetAllClassrooms();
            var filtered = allClassrooms.Where(c => 
                (typeFilter == "全部类型" || c.Type.ToString() == typeFilter) &&
                (string.IsNullOrEmpty(searchText) || 
                (!string.IsNullOrEmpty(c.ClassroomNumber) && c.ClassroomNumber.ToLower().Contains(searchText)) ||
                (!string.IsNullOrEmpty(c.Building) && c.Building.ToLower().Contains(searchText)) ||
                (!string.IsNullOrEmpty(c.Equipment) && c.Equipment.ToLower().Contains(searchText)))).ToList();

            dataGridViewClassrooms.DataSource = filtered;
            FormatDataGridView();
        }

        private System.Windows.Forms.DataGridView dataGridViewClassrooms;
        private System.Windows.Forms.Button btnAdd;
        private System.Windows.Forms.Button btnEdit;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.ComboBox comboBoxTypeFilter;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtSearch;
        private System.Windows.Forms.Label label2;
    }
}